import { app, BrowserWindow, Menu, ipcMain } from "electron";
import path from "path";
import { fileURLToPath } from "url";
import { menuTemplate } from "./menu";

/**
 * 常量、变量
 */
const currentDir = fileURLToPath(new URL(".", import.meta.url));

export let mainWindow: BrowserWindow | undefined;

const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);

/**
 * 初始化窗口
 */
async function createWindow() {
  mainWindow = new BrowserWindow({
    icon: path.resolve(currentDir, "icons/icon.png"),
    width: 1000,
    height: 700,
    minWidth: 768,
    minHeight: 512,
    useContentSize: true,
    webPreferences: {
      contextIsolation: true,
      preload: path.resolve(
        currentDir,
        path.join(
          process.env.QUASAR_ELECTRON_PRELOAD_FOLDER as string,
          "electron-preload" + process.env.QUASAR_ELECTRON_PRELOAD_EXTENSION,
        ),
      ),
    },
  });

  if (process.env.DEV) {
    await mainWindow.loadURL(process.env.APP_URL as string);
  } else {
    await mainWindow.loadFile("index.html");
  }

  if (process.env.DEBUGGING) {
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.webContents.on("devtools-opened", () => {
      mainWindow?.webContents.closeDevTools();
    });
  }

  mainWindow.on("closed", () => {
    mainWindow = undefined;
  });
}

/**
 * 程序开始
 */
void app.whenReady().then(createWindow);

/**
 * 监视
 */
app.on("window-all-closed", () => {
  app.quit();
});

app.on("activate", () => {
  if (mainWindow === undefined) {
    void createWindow();
  }
});

/**
 * ipc 监视
 */

// 退出应用
ipcMain.on("quit-app", () => {
  app.quit();
});
